<?php
	define('UTF32_BIG_ENDIAN_BOM', chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
	define('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
	define('UTF16_BIG_ENDIAN_BOM', chr(0xFE) . chr(0xFF));
	define('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
	define('UTF8_BOM', chr(0xEF) . chr(0xBB) . chr(0xBF));

class Zy extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		header("Content-type:text/html;charset=utf-8");
		
		$this->load->helper('form');
		$this->load->helper('url');
	}
	
	function index()
	{
		$this->load->view('Zy_view');
	}
	
	function search()
	{
		$this->load->view('Zy_view_search');
	}

	function export_old()
	{
		$this->load->library('table');
		$this->load->library('excel');
		
		$this->load->database();

		$dbtable = $this->load->get_var('dbtable');

		$querystring = "select * from $dbtable order by date desc";

		$query = $this->db->query($querystring);

		$this->excel->filename = '病例汇总';
		$this->excel->make_from_db($query);
	}

	function export_cond($querystring)
	{
		$query = $this->db->query($querystring);
 
		if(!$query)
		{
			return;
		}

		// Starting the PHPExcel library
		$this->load->library('PHPExcel');
		//$this->load->library('PHPExcel/IOFactory');

		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
		
		$objPHPExcel->setActiveSheetIndex(0);
		
		//PHPExcel_Calculation::getInstance()->cyclicFormulaCount = 1;
		
		// Field names in the first row
		$fields = $query->list_fields();
		$col = 0;
		foreach ($fields as $field)
		{
		   $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
		   $col++;
		}
		
		// Fetching the table data
		$row = 2;
		foreach($query->result() as $data)
		{
		   $col = 0;
		   foreach ($fields as $field)
		   {
		       $value = $data->$field;

		       if (!strcmp($field, "sex"))
		       {
		           $value = !strcmp($value, 'M') ? '男' : '女';
		       }

		       if (!strcmp($field, "age"))
		       {
		       		if ($value < 0)
		       		{
		       			$value = $value + 1000;
		       			$value .= "月";
		       		}
		       		else
		       		{
		       			$value .= "岁";
		       		}
		       }
		       
		       $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col, $row, $value, PHPExcel_Cell_DataType::TYPE_STRING);
		       $col++;
		   }
		
		   $row++;
		}
		
		$objPHPExcel->setActiveSheetIndex(0);
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		
		// Sending headers to force the user to download the file
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="bingli_'.date('dMy').'.xls"');
		header('Cache-Control: max-age=0');
		
		$objWriter->save('php://output');
	}

	function export()
	{
		$this->load->library('table');
		$this->load->database();

		$dbtable = $this->load->get_var('dbtable');
		$querystring = "select * from $dbtable order by date desc";
		
		$this->export_cond($querystring);	
	}

	function export_search()
	{
		$this->load->library('table');
		$this->load->database();

		$search_method = $this->input->get('search_method');
		$search_key = $this->input->get('search_key');

		$dbtable = $this->load->get_var('dbtable');

		$querystring = "";

		if (!strcmp($search_method, 'date'))
		{
			$querystring = "select * from $dbtable where date=str_to_date('$search_key', '%Y-%m-%d') order by `index` desc";
		}
		else if (!strcmp($search_method, 'month'))
		{
			$querystring = "select * from $dbtable where YEAR(date)=str_to_date('$search_key', '%Y-%m') and MONTH(date)=MONTH(str_to_date('$search_key', '%Y-%m')) order by `index` desc";
		}
		else if (!strcmp($search_method, 'year'))
		{
			$querystring = "select * from $dbtable where YEAR(date)=str_to_date('$search_key', '%Y') order by `index` desc";
		}
		else
		{
			$search_key_str = $this->db->escape_like_str($search_key);
			$querystring = "select * from $dbtable where $search_method like '%$search_key_str%' order by `index` desc";
		}
		
		$this->export_cond($querystring);	
	}
	
	function check_empty_value(&$value)
	{
		if (!$value)
		{
			$value = "";
		}
	}

	function importexcel()
	{
		$this->load->view('Zy_view_importexcel');
	}
	
	function upload(&$file)
	{
		$uploads_dir = "../uploads";

		if (!file_exists ($uploads_dir))
		{
			if (!mkdir($uploads_dir))
			{
				return -1;
			}
		}

		$config['upload_path'] = '../uploads/'; 
		$config['allowed_types'] = 'xls';
		$config['max_size'] = '10240';
		$config['remove_spaces'] = TRUE;
		
		$config['file_name'] = time();
		$this->load->library('upload', $config);

		$file = "";

		$fieldname = "patient_file1";
		$fieldvalue = $_FILES[$fieldname]['name'];

		if (empty($fieldvalue))
		{
			return -1;
		}

		if(!$this->upload->do_upload($fieldname))
		{
			echo $this->upload->display_errors();
			return -2;
		}
	
		$updata = $this->upload->data();
		$img = $updata['file_name'];

		$file = $img;

		return 0;
	}

	function findNum($str='')
	{
		$str=trim($str);
		if(empty($str)){return '0';}
		$result='';
		for($i=0;$i<strlen($str);$i++){
			if(is_numeric($str[$i])){
				$result.=$str[$i];
			}
		}
		return $result;
	}
	
	function importexceldone() 
	{
		$uploadDir = $this->load->get_var('uploaddir');
		
		if (!file_exists ($uploadDir))
		{
			if (!mkdir($uploadDir))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入病例失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
				return;
			}
		}

		$filename = $uploadDir."/bingli.xls";

		$tmpfile = $_FILES["patient_file1"]['tmp_name'];

		if (!is_uploaded_file($tmpfile))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入病例失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		if (!move_uploaded_file($tmpfile, iconv("utf-8","gb2312",$filename)))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入病例失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		if (!file_exists($filename))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入病例失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}

		$this->load->library('PHPExcel');
		$this->load->database();
		
		$dbtable = $this->load->get_var('dbtable');

		//防止最大可使用的内存总量过少
		if(intval(ini_get('memory_limit')) <= 100)
		{ 
		   ini_set('memory_limit','100M'); 
		}

		$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
		$objPHPExcel = $objReader->load($filename); //$filename可以是上传的文件，或者是指定的文件
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow(); // 取得总行数
		$highestColumn = $sheet->getHighestColumn(); // 取得总列数

		$fieldnames = array(
				'A' => 'index',
				'B' => 'name',
				'C' => 'sex',
				'D' => 'age',
				'E' => 'date',
				'F' => 'diag',
				'G' => 'prescribe',
				'H' => 'usemethod',
				'I' => 'comment',
				'J' => 'phonenum',
				'K' => 'addr',
				'L' => 'files',
			);

		foreach($fieldnames as $key => $val)
		{
			$fieldname = $objPHPExcel->getActiveSheet()->getCell($key.'1')->getValue();
			
			if (!$fieldname || strcmp($fieldname, $val))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入病例失败: excel格式不正确: ".$fieldname." -- ".$val."<a href=$url>回到病例汇总</a>";
				return;
			}
		}			

		//循环读取excel文件,读取一条,插入一条
		for($j = 2; $j <= $highestRow; $j++)
		{
			$patient_name = (string)$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();

			if (!$patient_name || !strcmp($patient_name, ""))
			{
				$patient_name = "某";
			}

			$patient_sex = (string)$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();

			if (!$patient_sex || !strcmp($patient_sex, "") || !strcmp($patient_sex, "男"))
			{
				$patient_sex = "M";
			}
			else
			{
				$patient_sex = "F";
			}
			
			$patient_age = (string)$objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();
			
			if (!$patient_age || !strcmp($patient_age, ""))
			{
				$patient_age = "0";
			}

			$age = $this->findNum($patient_age);
			
			if (strstr($patient_age, "月"))
			{
				$age -= 1000;
			}
			
			$patient_age = $age;
			
			$patient_date = (string)$objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();

			if (!$patient_date || !strcmp($patient_date, ""))
			{
				$patient_date = date("Y-m-d");
			}
			
			$patient_diag = (string)$objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();
			$this->check_empty_value($patient_diag);

			$patient_prescribe = (string)$objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();
			$this->check_empty_value($patient_prescribe);
			
			$patient_usemethod = (string)$objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();
			$this->check_empty_value($patient_usemethod);
			
			$patient_comment = (string)$objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();
			$this->check_empty_value($patient_comment);
			
			$patient_phonenum = (string)$objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();
			$this->check_empty_value($patient_phonenum);
			
			$patient_addr = (string)$objPHPExcel->getActiveSheet()->getCell("K".$j)->getValue();
			$this->check_empty_value($patient_addr);
			
			$patient_files = (string)$objPHPExcel->getActiveSheet()->getCell("L".$j)->getValue();
			$this->check_empty_value($patient_files);

			$patient_attackdate = (string)$objPHPExcel->getActiveSheet()->getCell("M".$j)->getValue();
			$this->check_empty_value($patient_attackdate);
			
			$data = array(
				'name' => $patient_name,
				'sex' => $patient_sex,
				'age' => $patient_age,
				'date' => $patient_date,
				'diag' => $patient_diag,
				'prescribe' => $patient_prescribe,
				'usemethod' => $patient_usemethod,
				'comment' => $patient_comment,
				'phonenum' => $patient_phonenum,
				'addr' => $patient_addr,
				'files' => $patient_files,
				'attackdate' => $patient_attackdate,
				);

			$querystring = $this->db->insert_string($dbtable, $data);

			if (!$this->db->query($querystring))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入病例失败！<a href=$url>回到病例汇总</a>";
				return;
			}
		}
		
		$data['title'] = '导入病例成功！';
		$data['linkstr'] = 'index.php/zy_caselist/index/0';
		$data['message'] = '回到病例汇总';
		
		$this->load->view('Zy_view_operationresult', $data);
	}

	function manageprescribe()
	{
		$this->load->view('Zy_view_prescribe');
	}
	
	function changebackground()
	{
		$this->load->view('Zy_view_changebackground');
	}
	
	function changebackgrounddone()
	{
		$this->load->database();

		$uploadDir = "../zydata";
		
		if (!file_exists ($uploadDir))
		{
			if (!mkdir($uploadDir))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "更换背景失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
				return;
			}
		}

		$filename = $uploadDir."/background.jpg";

		$tmpfile = $_FILES["background_file"]['tmp_name'];

		if (!is_uploaded_file($tmpfile))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "更换背景失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		if (!move_uploaded_file($tmpfile, iconv("utf-8","gb2312",$filename)))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "更换背景失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		if (!file_exists($filename))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "更换背景失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		$data['title'] = '更换背景成功！';
		$data['linkstr'] = 'index.php/zy_caselist/index/0';
		$data['message'] = '回到病例汇总';
		
		$this->load->view('Zy_view_operationresult', $data);
	}

	function systemsetting()
	{
		$data['reexam_check'] = $this->load->get_var('reexam_check');
		$data['table_bgcolor'] = $this->load->get_var('table_bgcolor');
		
		$this->load->view('Zy_view_systemsetting', $data);
	}
	
	function systemsettingdone()
	{
		$reexam_check=$this->input->post('reexam_check');
		$table_bgcolor=$this->input->post('table_bgcolor');
		$only_prtprescribe=$this->input->post('only_prtprescribe');
		
		if (!$reexam_check || strcmp($reexam_check, "on"))
		{
			$reexam_check = "off";
		}

		if (!$table_bgcolor || !strcmp(trim($table_bgcolor), ""))
		{
			$table_bgcolor = "none";
		}

		if (!$only_prtprescribe || strcmp($only_prtprescribe, "on"))
		{
			$only_prtprescribe = "off";
		}
		
		$this->varsphp->variables['reexam_check'] = $reexam_check;
		$this->varsphp->variables['table_bgcolor'] = $table_bgcolor;
		$this->varsphp->variables['only_prtprescribe'] = $only_prtprescribe;
		
		$this->varsphp->writecfg();

		$data['title'] = '设置成功！';
		$data['linkstr'] = 'index.php/zy_caselist/index/0';
		$data['message'] = '回到病例汇总';
		
		$this->load->view('Zy_view_operationresult', $data);
		$url = base_url().'index.php/zy_caselist/index/0';
	}
	
	function liuziqi()
	{
		$this->load->view('Zy_view_liuziqi');
	}
}

?>